import grpc
from concurrent import futures
import user_service_pb2
import user_service_pb2_grpc
import google.protobuf.empty_pb2 as empty

# 模拟数据库
fake_db = {}  # 存储用户名和密码
email_db = {}  # 存储邮箱和用户名对应关系

class UserService(user_service_pb2_grpc.UserServiceServicer):
    def __init__(self):
        self.logged_in = False  # 模拟一个简单的登录状态

    def Login(self, request, context):
        # 简单的用户名和密码验证
        if request.username in fake_db and fake_db[request.username] == request.password:
            self.logged_in = True
            return user_service_pb2.BoolResponse(success=True, message="Login successful.")
        else:
            return user_service_pb2.BoolResponse(success=False, message="Invalid username or password.")

    def IsLogin(self, request, context):
        # 返回用户是否已登录的状态
        return user_service_pb2.BoolResponse(success=self.logged_in)

    def Logout(self, request, context):
        # 执行退出登录
        self.logged_in = False
        return empty.Empty()  # 没有返回值

    def Register(self, request, context):
        # 检查用户名是否已存在
        if request.username in fake_db:
            return user_service_pb2.BoolResponse(success=False, message="Username already exists.")

        # 检查邮箱是否已被注册
        if request.email in email_db:
            return user_service_pb2.BoolResponse(success=False, message="Email already exists.")
        
        # 保存用户信息到 "数据库"
        fake_db[request.username] = request.password
        email_db[request.email] = request.username  # 将邮箱与用户名关联
        
        return user_service_pb2.BoolResponse(success=True, message="Registration successful.")

# 启动 gRPC 服务
def serve():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    user_service_pb2_grpc.add_UserServiceServicer_to_server(UserService(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    print("Server started at port 50051.")
    server.wait_for_termination()

if __name__ == '__main__':
    serve()